package cn.onein.edu.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.onein.edu.biz.bean.Item;
import cn.onein.edu.biz.bean.Order;
import cn.onein.edu.biz.bean.Product;
import cn.onein.edu.biz.bean.User;
import cn.onein.edu.common.OrderStatusType;
import cn.onein.edu.common.ProductType;
import cn.onein.edu.util.DateUtil;
import cn.onein.edu.util.StringUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.service.LearnService;
import cn.onein.edu.web.service.PaymentService;
import cn.onein.edu.web.util.CenterHotContentUtil;
import cn.onein.edu.web.vo.ItemVO;
import cn.onein.edu.web.vo.OrderVO;
import cn.onein.edu.web.vo.ProductVO;

@Controller
public class MemberServiceController extends BaseController {
	
	Logger logger = Logger.getLogger(MemberServiceController.class);
	
	@Autowired
	private PaymentService paymentService;
	
	@Autowired
	private LearnService learnService;
	
	private static final String MEMBERSTATUS = "MEMBERSTATUS";
	
	private static final String SUBDAYS = "SUBDAYS";
	
	private final static String ORDER = "ORDER";
	
	private final static String RENEW = "RENEW";
	
	private final static String CREATE = "Create";
	
	/**
	 * 会员服务
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center/memberService", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView memberService(HttpServletResponse resp,HttpServletRequest req) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Order> orderList = null;
		
		// 得到登录用户信息
		User user = this.getLoginUser(req);
		
		try{
		    orderList = paymentService.getOrderByUserId(user.getId());
		}catch(Exception e){
			logger.error("query order status error.",e);
			return new ModelAndView("error");
		}
		
		if (user.getLevelExpires() == null || orderList == null || orderList.isEmpty()) {
			// 没有订单 或者过期时间为空
			param.put(MEMBERSTATUS, null);
		} else {
			//过期时间到现在间隔天数
			int days = DateUtil.daysOfTwo(new Date(), user.getLevelExpires());
			if(days > 0){
				param.put(SUBDAYS, days);
				param.put(MEMBERSTATUS, Boolean.TRUE);
			}else{
				//已经过期
				param.put(MEMBERSTATUS, Boolean.FALSE);
			}
		}
		
		//得到用户中心最新资讯文章
		CenterHotContentUtil.initHotContent(req, user, learnService, param);
		
		List<OrderVO> vos = this.convertOrderListVO(orderList);
		
		param.put("orders", vos);
		param.put("user", user);
		
		setMenu(param, MENU_VALUE_MEMBER_SERVICE);
		return new ModelAndView("center/memberService", param);
	}
	
	/**
	 * 用户订单取消
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center/cancelOrder", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView cancelOrder(String orderNo,HttpServletResponse resp,HttpServletRequest req) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Order> orderList = null;
		
		// 得到登录用户信息
		User user = this.getLoginUser(req);
		
		Order order = paymentService.getOrderByOrderNo(orderNo);
		if(order == null){
			return new ModelAndView("resourceNotFound");
		}
		if(CREATE.equals(order.getOrderStatus().toString())){
			try{
				paymentService.updateOrderStatusByOrderNo(orderNo, OrderStatusType.UserCancel);
			}catch(Exception e){
				logger.error("update order status error.",e);
				return new ModelAndView("error");
			}
		}
		
		try{
		    orderList = paymentService.getOrderByUserId(user.getId());
		}catch(Exception e){
			logger.error("query order status error.",e);
			return new ModelAndView("error");
		}
		
		if (user.getLevelExpires() == null || orderList == null || orderList.isEmpty()) {
			// 没有订单 或者过期时间为空
			param.put(MEMBERSTATUS, null);
		} else {
			//过期时间到现在间隔天数
			int days = DateUtil.daysOfTwo(new Date(), user.getLevelExpires());
			if(days > 0){
				param.put(SUBDAYS, days);
				param.put(MEMBERSTATUS, Boolean.TRUE);
			}else{
				//已经过期
				param.put(MEMBERSTATUS, Boolean.FALSE);
			}
		}
		
		List<OrderVO> vos = this.convertOrderListVO(orderList);
		
		param.put("orders", vos);
		param.put("user", user);
		
		setMenu(param, MENU_VALUE_MEMBER_SERVICE);
		
		return new ModelAndView("center/memberService", param);
	}
	
	/**
	 * 用户订单取消
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center/orderPay", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView orderPay(Long orderId,String orderNo,HttpServletResponse resp,HttpServletRequest req) throws Exception {
	    List<Product> products = new ArrayList<Product>();
	    Map<String, Object> param = new HashMap<String, Object>();
	    Order order = null;
	    
	    try{
	    	List<Item> items = paymentService.getItemByOrderId(orderId);
			for(Item item : items){
				Product procduct = paymentService.getProductById(item.getProductId());
				products.add(procduct);
			}
			
		   order = paymentService.getOrderByOrderNo(orderNo);
	    }catch(Exception e){
	    	logger.error("order pay error", e);
	    }
	    
		param.put("products", convertProductVO(products));
		param.put("order", convertOrderVO(order));
		
		this.setMenu(param, MENU_VALUE_PAYMENT);

		return new ModelAndView("payment/select", param);
		
	}
	
	/**
	 * 会员订购和续订
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center/memberRenew", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView memberRenew(String type,HttpServletResponse resp,HttpServletRequest req) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Product> products = null;
		
		if(type == null || "".equals(type)){
			return new ModelAndView("resourceNotFound");
		}
		
		if(ORDER.equals(type)){
			products = paymentService.getProductByType(ProductType.OfficialBase.ordinal());
		}else if(RENEW.equals(type)){
			products = paymentService.getProductByType(ProductType.Continuation.ordinal());
		}
		
		param.put("products", convertProductVO(products));
		setMenu(param, MENU_VALUE_MEMBER_SERVICE);
		
		return new ModelAndView("center/memberrenew", param);
	}
	
	private List<ProductVO> convertProductVO(List<Product> products){
		List<ProductVO> vos = new ArrayList<ProductVO>();
		for (Product o : products) {
			ProductVO vo = new ProductVO();
			vo.setId(o.getId().toString());
			vo.setName(o.getName());
			vo.setPrice(StringUtil.fenToYuan(o.getPrice()));
			vo.setDescription(o.getDescription());
			vo.setType(o.getType().toString());
			vos.add(vo);
		}
		return vos;
	}
	
	private OrderVO convertOrderVO(Order order){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		OrderVO vo = new OrderVO();
		vo.setId(order.getId());
		vo.setAmount(StringUtil.fenToYuan(order.getAmount()));
		vo.setOrderDate(df.format(order.getOrderDate()));
		vo.setOrderNo(order.getOrderNo());
		vo.setOrderStatus(order.getOrderStatus() == null ? "&nbsp; " : order.getOrderStatus().toString());
		vo.setPaymentType(order.getPaymentType() == null ? " &nbsp;" : order.getPaymentType().toString());
	    vo.setOrderFrom(order.getOrderFrom() == null ? "&nbsp;" : order.getOrderFrom().toString());
	    
	    return vo;
	}
	
    private List<OrderVO> convertOrderListVO(List<Order> orders){
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    	List<OrderVO> vos = new ArrayList<OrderVO>();
    	
    	for(Order order : orders){
    		OrderVO vo = new OrderVO();
    		vo.setId(order.getId());
    		vo.setAmount(StringUtil.fenToYuan(order.getAmount()));
    		vo.setOrderDate(df.format(order.getOrderDate()));
    		vo.setOrderNo(order.getOrderNo());
    		if(DateUtil.daysOfTwo(order.getOrderDate(),new Date() ) > 3){
    			vo.setOrderCancel(Boolean.TRUE);
    		}
    		
    		vo.setOrderStatus(order.getOrderStatus() == null ? "&nbsp; " : order.getOrderStatus().toString());
    		vo.setPaymentType(order.getPaymentType() == null ? " &nbsp;" : order.getPaymentType().toString());
    	    vo.setOrderFrom(order.getOrderFrom() == null ? "&nbsp;" : order.getOrderFrom().toString());
    	    
    		List<Item> items = paymentService.getItemByOrderId(order.getId());
    		List<ItemVO> itemVOS = new ArrayList<ItemVO>();
    		for(Item item : items){
    			Product product = paymentService.getProductById(item.getProductId());
    			ItemVO itemVO = new ItemVO();
    			itemVO.setPrice(StringUtil.fenToYuan(item.getAmount()));
    			itemVO.setName(product.getName());
    			itemVO.setType(product.getType().toString());
    			itemVOS.add(itemVO);
    		}
    		vo.setItems(itemVOS);
    		
    		vos.add(vo);
    	}
    	
    	return vos;
	}
    
}

